<template>
    <div class="router-view-wrapper technology-route-management" @mouseup="handleOnwrapperClick">
        <div>
            <el-scrollbar class="route-tree-wrapper">
                <el-tree ref="treeRef" :data="states.technologyRouteList" @node-contextmenu="handleNodeRightClick"
                    node-key="id" empty-text=""
                    :default-expanded-keys="[`TechnologyState_Enabled`, `TechnologyState_Disabled`]" highlight-current
                    @node-click="handleNodeClick">
                    <template #default="{ node, data }">
                        <span :class="getTreeClassName(data, node)">
                            {{ getTreeNodeName(data) }}
                        </span>
                    </template>
                </el-tree>
            </el-scrollbar>
            <div class="context-menu"
                v-if="states.pageConfig.buttonList.filter(button => button.menuPositionCode === `MenuPosition_RightCick`).length > 0"
                :style="states.menuContextStyle">
                <el-menu mode="vertical" active-text-color="#000" background-color="aliceblue" text-color="#000">
                    <el-menu-item
                        v-for="button in states.pageConfig.buttonList.filter(button => button.menuPositionCode === `MenuPosition_RightCick`)"
                        :index="button.id" @click="handleOnContextMenuButtonClick(button)">
                        <img class="icon-button" :src="`/image/${button.icon}`" alt="" />
                        <span>{{ button.name }}</span>
                    </el-menu-item>
                </el-menu>
            </div>
        </div>
        <div class="process-table-wrapper">
            <div class="button-bar-wrapper"
                v-if="states.pageConfig.buttonList.filter(button => button.menuPositionCode === `MenuPosition_ButtonBar`).length > 0">
                <el-button type="primary" @click="handleOnButtonClick(button)"
                    v-for="button in states.pageConfig.buttonList.filter(button => button.menuPositionCode === `MenuPosition_ButtonBar`)">
                    {{ button.name }}
                </el-button>
            </div>
            <DataTable class="data-table" :data="states.data" :columnList="states.pageConfig.columnList"
                :dictionary="states.pageConfig.dictionary" ref="tableRef" :sortable="false"
                :buttonList="states.pageConfig.buttonList.filter(button => button.menuPositionCode === `MenuPosition_Row`)"
                :onButtonClick="handleOnButtonClick" :pagination="false" />
        </div>
        <EditDialog ref="editDialogRef" :visible="states.editDialog.visible" :title="states.editDialog.button.name"
            :on-cancel="handleOnEditDialogCancel" :on-confirm="handelOnEditDialogConfirm" />
    </div>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { lang } from '../../lang';
import EditDialog from "../../components/EditDialog.vue";
import DataTable from "../../components/DataTable.vue";

const route = useRoute();
const treeRef = ref();
const editDialogRef = ref();
const tableRef = ref();

const props = defineProps([
    "request",
    "success",
    "warning",
    "info",
    "error",
    "loading",
    "confirm",
    "closeLoading",
]);

const states = reactive({
    pageConfig: {
        id: "",
        name: "",
        icon: "",
        typeCode: "",
        menuPositionCode: 0,
        url: "",
        columnList: [],
        buttonList: [],
        dictionary: {},
    },
    menuContextStyle: { left: `100px`, top: `100px`, display: `none` },
    editDialog: {
        visible: false,
        button: {
            id: "",
            name: "",
            icon: "",
            typeCode: "",
            menuPositionCode: 0,
            url: "",
            columnList: [],
        }
    },
    technologyRouteList: [
        { id: "TechnologyState_Enabled", name: `${lang.ENABLED}`, children: [] },
        { id: "TechnologyState_Disabled", name: `${lang.DISABLED}`, children: [] }
    ],
    data: {
        total: 0,
        rows: []
    },
});

const showContextMenu = async (x, y) => {
    states.menuContextStyle = { left: `${x}px`, top: `${y}px`, display: `block` };
};

const hideContextMenu = async () => {
    states.menuContextStyle = { left: `0px`, top: `0px`, display: `none` };
};

const showEditDialog = async (button, value) => {
    let response = await props.request("System/GetDictionary", { menuId: button.id });
    if (response.Code !== "S") {
        props.error(response.Msg);
        return;
    }

    states.editDialog.button = button;
    editDialogRef.value.setValue(button.typeCode, value, button.columnList, response.Data.dictionary);
    states.editDialog.visible = true;
};

const hideEditDialog = async () => {
    states.editDialog.visible = false;
};

const handleOnContextMenuButtonClick = async (button) => {
    let treeNode = treeRef.value.getCurrentNode();
    switch (button.typeCode) {
        case "MenuType_AddButton":
            showEditDialog(button, { id: 0 });
            break;
        case "MenuType_EditButton":
            if (treeNode.id === "TechnologyState_Enabled" || treeNode.id === "TechnologyState_Disabled") {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }

            showEditDialog(button, treeNode);
            break;
        case "MenuType_BatchEditButton":
            props.warning(`${lang.DONT_SUPPORT_BUTTON_TYPE}!`);
            break;
        case "MenuType_ViewButton":
            if (treeNode.id === "TechnologyState_Enabled" || treeNode.id === "TechnologyState_Disabled") {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }

            break;
        case "MenuType_ExportButton":
            break;
        case "MenuType_OperationButton":
            if (treeNode.id === "TechnologyState_Enabled" || treeNode.id === "TechnologyState_Disabled") {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }

            props.confirm(`${lang.MAKE_SURE_TO}${button.name}?`, async () => {
                let value = treeNode;
                let response = await props.request(button.url, {
                    menuId: button.id,
                    value: value,
                    query: {},
                    selectedIds: [value.id],
                });

                if (response.Code === "S") {
                    props.success(response.Msg);
                    getTechnologyRouteList();
                } else {
                    props.error(response.Msg);
                }
            });
            break;
    }

};

const handleOnButtonClick = async (button) => {
    let tableSelectionRows = tableRef.value.getSelectionRows();
    let treeNode = treeRef.value.getCurrentNode();
    if (!treeNode) {
        props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
        return;
    }
    switch (button.typeCode) {
        case "MenuType_AddButton":
            showEditDialog(button, { id: 0, technology_route_code: treeNode.code });
            break;
        case "MenuType_EditButton":
            if (tableSelectionRows.length === 0) {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }
            showEditDialog(button, tableSelectionRows[0]);
            break;
        case "MenuType_BatchEditButton":
            if (tableSelectionRows.length === 0) {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }
            showEditDialog(button, { id: 0 });
            break;
        case "MenuType_ViewButton":
            if (tableSelectionRows.length === 0) {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }
            break;
        case "MenuType_ExportButton":
            break;
        case "MenuType_OperationButton":
            if (tableSelectionRows.length === 0) {
                props.warning(`${lang.PLEASE_SELECT_DATA_TO_OPERATE}!`);
                return;
            }

            props.confirm(`${lang.MAKE_SURE_TO}${button.name}?`, async () => {
                let value = tableSelectionRows[0];
                let query = searchDrawerRef.value.getQuery();
                let selectedIds = tableSelectionRows.map(row => row.id.toString());
                let response = await props.request(button.url, {
                    menuId: button.id,
                    value: value,
                    query: query,
                    selectedIds: selectedIds,
                });

                if (response.Code === "S") {
                    props.success(response.Msg);
                    getTechnologyRouteList();
                } else {
                    props.error(response.Msg);
                }
            });
            break;
    }
};

const handleOnEditDialogCancel = async () => {
    hideEditDialog();
};

const handelOnEditDialogConfirm = async () => {
    let treeNode = treeRef.value.getCurrentNode();
    let value = editDialogRef.value.getValue();
    let tableSelectionRows = tableRef.value.getSelectionRows();
    let selectedIds = tableSelectionRows.map(row => row.id.toString());
    let response = await props.request(states.editDialog.button.url, {
        menuId: states.editDialog.button.id,
        value: value,
        query: {},
        selectedIds: selectedIds,
    });

    if (response.Code === "S") {
        props.success(response.Msg);
        hideEditDialog();
        getTechnologyRouteList(treeNode);
    } else {
        props.error(response.Msg);
    }
};

const handleOnwrapperClick = async (e) => {
    hideContextMenu();
};

const handleNodeRightClick = async (e, data, node) => {
    treeRef.value.setCurrentKey(data.id);
    getTechnologyRouteProcessList();
    showContextMenu(e.pageX, e.pageY);
};

const handleNodeClick = async (e) => {
    getTechnologyRouteProcessList();
    hideContextMenu();
};

const getTreeClassName = (data, node) => {
    if (data.id === "TechnologyState_Enabled" || data.state_code === "TechnologyState_Enabled") {
        return "tree-green-node";
    } else if (data.id === "TechnologyState_Disabled" || data.state_code === "TechnologyState_Disabled") {
        return "tree-red-node";
    }

    return null;
};

const getTreeNodeName = (data) => {
    if (data.id === "TechnologyState_Enabled" || data.id === "TechnologyState_Disabled") {
        return data.name;
    } else {
        return `${data.sort_number}.${data.code}-${data.name}`;
    }
};

const getTechnologyRouteList = async (node) => {
    let response = await props.request("Technology/GetTechnologyRouteList", {});
    if (response.Code === "S") {
        states.technologyRouteList[0].children = response.Data.filter(technologyRoute => technologyRoute.state_code === "TechnologyState_Enabled");
        states.technologyRouteList[1].children = response.Data.filter(technologyRoute => technologyRoute.state_code === "TechnologyState_Disabled");
        if (node) {
            treeRef.value.setCurrentKey(node.id);
        }
        getTechnologyRouteProcessList();
    } else {
        props.error(response.Msg);
    }
};

const getTechnologyRouteProcessList = async () => {
    let node = treeRef.value.getCurrentNode();
    if (node === undefined || node === null || node.id === "TechnologyState_Enabled" || node.id === "TechnologyState_Disabled") {
        states.data = {
            total: 0,
            rows: [],
        };
    } else {
        let response = await props.request("Technology/GetTechnologyRouteProcessList", { technology_route_code: node.code });
        if (response.Code === "S") {
            states.data = {
                total: response.Data.length,
                rows: response.Data,
            };
        } else {
            props.error(response.Msg);
        }
    }
};

const getMenuConfig = async (menuId) => {
    let response = await props.request("System/GetPageConfig", { menuId: menuId });
    if (response.Code === "S") {
        states.pageConfig = response.Data;
    } else {
        props.error(response.Msg);
    }
};

const initialize = async () => {
    let menuId = route.query.id;
    await getMenuConfig(menuId);
    await getTechnologyRouteList();
};

onMounted(() => {
    initialize();
});
</script>
<style scoped lang="less">
@import "../../index.less";
@route-tree-wrapper-width: 300px;
@button-bar-height: 60px;

.technology-route-management {
    display: flex;

    .route-tree-wrapper {
        width: calc(~"@{route-tree-wrapper-width} - 1px");
        height: calc(~"@{page-wrapper-height} - @{header-height}");
        border-right: 1px solid #f1f1f1;
    }

    .context-menu {
        position: absolute;
        z-index: 99;
        background-color: aliceblue;

        .icon-button {
            width: 18px;
            height: 18px;
        }
    }

    .process-table-wrapper {
        width: calc(~"@{page-wrapper-width} - @{sider-width} - @{route-tree-wrapper-width}");
        height: calc(~"@{page-wrapper-height} - @{header-height}");

        .button-bar-wrapper {
            height: @button-bar-height;
            width: calc(~"100% - 20px");
            display: flex;
            justify-content: start;
            align-items: center;
            margin: 0 10px;
        }

        .data-table {
            height: calc(~"@{page-wrapper-height} - @{header-height} - @{button-bar-height} - 10px");
            width: calc(~"100% - 20px");
            margin: 0 10px;
        }
    }
}
</style>
  